﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Manyor.Net;

namespace ManyorSync
{
    public partial class MainForm : Form
    {
        //SocketServer server;
        SocketClient socketClient;
        CommandDispatcher dispatcher;
        ClientFileTransfer cft;
        public MainForm()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {           
            //server.StartServer();
            if (socketClient.ConnectServer())
            {
                btn_Start.Enabled = false;
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            socketClient = new SocketClient(new Action<byte[], int>(ReceiverMessage));
            dispatcher = new CommandDispatcher();
            cft = new ClientFileTransfer(new Action<byte[]>(SendMessage));
            cft.OnFileTransProcessChanged += new EventHandler(cft_OnFileTransProcessChanged);
            cft.OnFileTransComplate += new EventHandler(cft_OnFileTransComplate);
            dispatcher.RegisterCommand(cft, CommandCode.COMMAND_TRANSFER,CommandCode.COMMAND_CONNECT_OK);
        }

        void cft_OnFileTransComplate(object sender, EventArgs e)
        {
            //throw new NotImplementedException();
            MessageBox.Show("传输完成！");
        }

        void cft_OnFileTransProcessChanged(object sender, EventArgs e)
        {
            
            //throw new NotImplementedException();
            FileEventArgs arg = e as FileEventArgs;
            int val=(int)arg.TransferedPercent;
            //this.progressBar1.Value = val;
            System.Console.WriteLine("%:"+val);
            Action<int> ac = new Action<int>((a) => { this.progressBar1.Value = a; });
            this.Invoke(ac, val);
        }


        //void UpdateProcess(int val)
        //{
        //    this.progressBar1.Value =val;// ..(int)arg.TransferedPercent * 100;}
        //}

        /// <summary>
        /// 接收消息
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="length"></param>
        public  void ReceiverMessage(byte[] bytes, int length)
        {            
            dispatcher.DoTask(bytes, length);
        }

        public void SendMessage(byte[] bytes)
        {
            socketClient.SendMessage(bytes);
        }

        private void btn_chooseFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileDialog1 = new OpenFileDialog();
            if (fileDialog1.ShowDialog() == DialogResult.OK)
            {
                //cft.FilePath = fileDialog1.FileName;
                cft.ReadyTransferFile(fileDialog1.FileName);
            }
        }
    }
}
